package com.morgan.maxfunding;



import com.han.utility.PlacesAutoCompleteAdapter;

import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.Toast;

public class HomeActivity extends Activity implements OnItemClickListener {
	
	LinearLayout llytHeader;

	EditText edtLoanAmount;
	EditText edtFirstName;
	EditText edtMiddleName;
	EditText edtSureName;
//	EditText edtBirthday;
	Button		btnBirthday;
	EditText edtLicense;
	EditText edtMobilePhone;
	EditText edtHomePhone;
	EditText edtEmail;
	
	String 		strMobilePhone;
	String		strHomePhone;
	
	AutoCompleteTextView  edtHomeAddress;  //  AutoCompleteTextView
	
	EditText edtOtherPurpose;
	
	Spinner spnTitle;
	Spinner spnCitizenShip;
	Spinner spnResidentialStatus;
//	Spinner spnNumberOfDependant;
	Spinner spnLoanPurpose;
	
//	Button btnNeedHelp;
//	Button btnGoSite;
//	Button btnBefore;
	Button btnNext;
	
	Button btnInfFirstName;
	Button btnInfSureName;
	Button btnInfMobilePhone;
	Button btnRemoveHomePhone;
	Button btnInfEmail;
	
	
	ScrollView scrollView;
//	Button btnInfNumberDependant;
	
	static final int DATE_DIALOG_ID = 999;
	
	private int year;
	private int month;
	private int day;
	
	public static SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        
        initWidget();
        initEvent();
        initValue();
    }
    
    private void initWidget() {
    	
    	// Spinnner
		llytHeader			= (LinearLayout) findViewById(R.id.header_linearLayout);

    	scrollView = (ScrollView) findViewById(R.id.scrollView1);
    	
    	spnTitle = (Spinner) findViewById(R.id.number_of_motor_vehicle_spinner);
    	spnCitizenShip = (Spinner) findViewById(R.id.citizenship_spinner);
    	spnResidentialStatus = (Spinner) findViewById(R.id.residential_status_spinner);
//    	spnNumberOfDependant = (Spinner) findViewById(R.id.number_dependant_spinner);
    	spnLoanPurpose = (Spinner) findViewById(R.id.loan_poupose_spinner);
    	
    	// EditText
    	
    	edtLoanAmount = (EditText) findViewById(R.id.loan_amount_editText);
    	edtFirstName = (EditText) findViewById(R.id.firstName_editText);
    	edtMiddleName = (EditText) findViewById(R.id.partner_name_editText);
    	edtSureName = (EditText) findViewById(R.id.current_value_editText1);
    	btnBirthday = (Button) findViewById(R.id.birthday_button);
    	edtLicense = (EditText) findViewById(R.id.license_editText);
    	edtMobilePhone = (EditText) findViewById(R.id.mobilePhone_editText);
    	edtHomePhone = (EditText) findViewById(R.id.homePhone_editText);
    	edtEmail = (EditText) findViewById(R.id.email_editText);
    	
    	edtHomeAddress = (AutoCompleteTextView) findViewById(R.id.address_editText); // AutoCompleteTextView
    	edtOtherPurpose = (EditText) findViewById(R.id.ohter_purpose_editText);
    	
    	// Button
    	
//    	btnNeedHelp = (Button) findViewById(R.id.need_help_button);
//    	btnGoSite = (Button) findViewById(R.id.go_site_button);
//    	btnBefore = (Button) findViewById(R.id.back_button);
    	btnNext = (Button) findViewById(R.id.next_button);
    	
    	btnInfFirstName = (Button) findViewById(R.id.inf_firstName_button);
    	btnInfSureName = (Button) findViewById(R.id.inf_current_value_button1);
    	btnInfMobilePhone = (Button) findViewById(R.id.inf_mobilePhone_button);
    	btnRemoveHomePhone = (Button) findViewById(R.id.remove_home_phone_button);
    	btnInfEmail = (Button) findViewById(R.id.inf_email_button);
//    	btnInfNumberDependant = (Button) findViewById(R.id.inf_number_dependant);
    	edtLoanAmount.setFocusableInTouchMode(true);
    	edtFirstName.setFocusableInTouchMode(true);
    	edtMiddleName.setFocusableInTouchMode(true);
    	edtSureName.setFocusableInTouchMode(true);

//    	edtLoanAmount.requestFocus();
    }
    
    private void initValue() {
    	
		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfTitle);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnTitle.setAdapter(spinnerArrayAdapter);
		
		spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfCitizeShip);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnCitizenShip.setAdapter(spinnerArrayAdapter);
		
		spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfResidentialStatus);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnResidentialStatus.setAdapter(spinnerArrayAdapter);
		
//		spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfNumberDependant);
//		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
//		spnNumberOfDependant.setAdapter(spinnerArrayAdapter);
		
		spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfLoanPurpose);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnLoanPurpose.setAdapter(spinnerArrayAdapter);
		
        edtHomeAddress.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
        edtHomeAddress.setOnItemClickListener(this);

		year = 1983;
		month = 0;
		day = 1;
		
		Configuration config = getResources().getConfiguration();
		int size = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;

		if (size == Configuration.SCREENLAYOUT_SIZE_SMALL)
		{
		    // use special layout for small screens
			GlobalData.strScreenType = "galaxy s1";
		}
		if (size == Configuration.SCREENLAYOUT_SIZE_NORMAL)
		{
		    // use special layout for small screens
			GlobalData.strScreenType = "galaxy s4";
		}
		if (size == Configuration.SCREENLAYOUT_SIZE_SMALL)
		{
		    // use special layout for small screens
			GlobalData.strScreenType = "galaxy s3";
		}
		if (size == Configuration.SCREENLAYOUT_SIZE_LARGE)
		{
		    // use special layout for small screens
			GlobalData.strScreenType = "galaxy s2";
		}
		if (size == Configuration.SCREENLAYOUT_SIZE_XLARGE)
		{
		    // use special layout for small screens
			GlobalData.strScreenType = "galaxy s4 Tablet";
		}
		
		// set current date into textview
		
		loadSavedPreferences();
    }
    
    private void initEvent() {

    	edtLoanAmount.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus) {
                	String str = edtLoanAmount.getText().toString();
                	
                	int nLoanAmount = 0;
                	
                	if (!str.equals("")) {
                		nLoanAmount = Integer.parseInt(str);
                		if (nLoanAmount < 1000) {
                			new AlertDialog.Builder(HomeActivity.this)
                            .setTitle("Input")
                            .setMessage("The minimum loan amount is $1000")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) { 
                                    // continue with delete
                                	edtLoanAmount.requestFocusFromTouch();
                                }
                             })
                            .show();
                    		scrollView.scrollTo(0, edtLoanAmount.getTop() - 30);
                    	}
                	} else {
                		new AlertDialog.Builder(HomeActivity.this)
                        .setTitle("Input")
                        .setMessage("Please input value Loan Amount!")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) { 
                                // continue with delete
                            	edtLoanAmount.requestFocusFromTouch();
                            }
                         })
                        .show();
                		scrollView.scrollTo(0, edtLoanAmount.getTop() - 30);
                	}
                }
            }
        });
    	
		llytHeader.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maxfunding.com.au"));
				startActivity(browserIntent);
			}
        });
		
    	edtMobilePhone.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {

              // you can call or do what you want with your EditText here
            	String str = edtMobilePhone.getText().toString();
            	int l = str.length();
            	if (l > 10) {
                	strMobilePhone = str.substring(0, 10);
            		edtMobilePhone.setText(strMobilePhone);
            		edtMobilePhone.setSelection(10);
            	}
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
    	
    	edtFirstName.setOnFocusChangeListener(new OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus) {
                	String str = edtFirstName.getText().toString();
                	if (str.length() > 0) {
                		String firstLetter = str.substring(0, 1);
                		firstLetter = firstLetter.toUpperCase();
                    	String lastLetter = str.substring(1);
                    	lastLetter = lastLetter.toLowerCase();
                    	edtFirstName.setText(firstLetter + lastLetter);
                	}
                } 
            }
        });
    	
    	edtMiddleName.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus) {
                	String str = edtMiddleName.getText().toString();
                	if (str.length() > 0) {
                		String firstLetter = str.substring(0, 1);
                		firstLetter = firstLetter.toUpperCase();
                    	String lastLetter = str.substring(1);
                    	lastLetter = lastLetter.toLowerCase();
                    	edtMiddleName.setText(firstLetter + lastLetter);
                	}
                } 
            }
        });
    	
    	edtSureName.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus) {
                	String str = edtSureName.getText().toString();
                	if (str.length() > 0) {
                		edtSureName.setText(str.toUpperCase());
                	}
                } 
            }
        });
    	
    	edtHomePhone.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
              // you can call or do what you want with your EditText here
            	String str1 = edtHomePhone.getText().toString();
            	int l = str1.length();
            	if (l > 10) {
            		strHomePhone = str1.substring(0, 10);
            		edtHomePhone.setText(strHomePhone);
            		edtHomePhone.setSelection(10);
            	}
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
    	
//    	btnNeedHelp.setOnClickListener(new Button.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				final AlertDialog.Builder alert = new AlertDialog.Builder(HomeActivity.this);
//			    final EditText input = new EditText(HomeActivity.this);
//			    alert.setTitle("What issues are you experiencing?");
//			    alert.setView(input);
//			    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//			        public void onClick(DialogInterface dialog, int whichButton) {
////			            dialog.cancel();
//			        }
//			    });
//			    alert.setPositiveButton("Talk to Us", new DialogInterface.OnClickListener() {
//			        public void onClick(DialogInterface dialog, int whichButton) {
//			        	 Intent email = new Intent(Intent.ACTION_SEND_MULTIPLE);
//			        	 email.putExtra(Intent.EXTRA_EMAIL, new String[] {"victor@morganfinance.com.au"});
//			             email.putExtra(Intent.EXTRA_SUBJECT, "Mobile App technical error report");
//			             email.putExtra(Intent.EXTRA_TEXT, input.getText().toString());
//			        	 email.setType("text/plain");
//
//			             startActivity(Intent.createChooser(email, "E-mail"));
//			        }
//			    });
//			    
//			    alert.show();
//			}
//        });
//    	
//    	btnGoSite.setOnClickListener(new Button.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.morganfinance.com.au/mobile_index.php"));
//				startActivity(browserIntent);
//			}
//        });
//    	
//    	btnBefore.setOnClickListener(new Button.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//
//			}
//        });
    	
    	btnNext.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				next();
			}
        });
    	
    	btnInfFirstName.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showGeneralAlert("", "As it appears on your driver's licence");
			}
        });
    	
    	btnInfSureName.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showGeneralAlert("", "As it appears on your driver's licence");
			}
        });
    	
    	btnInfMobilePhone.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showGeneralAlert("", "eg:0400 000 000");
			}
        });
    	
    	btnRemoveHomePhone.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				
			}
        });
    	
    	btnInfEmail.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showGeneralAlert("", "Email is crucial for communication during the application process");
			}
        });
    	
//    	btnInfNumberDependant.setOnClickListener(new Button.OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				showGeneralAlert("", "No. of dependant under 18 + No. of persons relying solely on your income for living expenses.\n Note: " +
//						"Do not include your partner if he/she receives wage/certrelink benefits");
//			}
//        });
    	
    	btnBirthday.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
        });
    }
    
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        String str = (String) adapterView.getItemAtPosition(position);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }
    
    protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
		   // set date picker as current date
		   return new DatePickerDialog(this, datePickerListener, 
                         year, month, day);
		}
		return null;
	}
 
	private DatePickerDialog.OnDateSetListener datePickerListener 
                = new DatePickerDialog.OnDateSetListener() {
 
		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;
 
			// set selected date into textview
			
			
			String strMonth = Integer.toString(month + 1);
			String strDay	= Integer.toString(day);
			if (month < 9) 
				strMonth = "0" + strMonth;
			if (day < 10)
				strDay = "0" + strDay;
			
			btnBirthday.setText(new StringBuilder().append(strDay)
			   .append("/").append(strMonth).append("/").append(year)); 
		}
	};
    
    public void showGeneralAlert(String title, String message) {
    	new AlertDialog.Builder(HomeActivity.this)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // continue with delete
            }
         })
         .show();
    }
    
    public void loadSavedPreferences() {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        
        String str;
        int n;
        
        str = sharedPreferences.getString("strLoanAmount", "");
        edtLoanAmount.setText(str);
        n = sharedPreferences.getInt("nTitle1", 0);
        spnTitle.setSelection(n);
        str = sharedPreferences.getString("strFirstName1", "");
        edtFirstName.setText(str);
        str = sharedPreferences.getString("strMiddleName1", "");
        edtMiddleName.setText(str);
        str = sharedPreferences.getString("strSurname1", "");
        edtSureName.setText(str);
        n = sharedPreferences.getInt("nResidency", 0);
        spnCitizenShip.setSelection(n);
        str = sharedPreferences.getString("strDOB", "01/01/1983");
        btnBirthday.setText(str);
        
        String str1;
        str1 = str.substring(0, 2);
        day = Integer.parseInt(str1);
        str1 = str.substring(3, 5);
        month = Integer.parseInt(str1) - 1;
        str1 = str.substring(6, 10);
        year = Integer.parseInt(str1);
        
        str = sharedPreferences.getString("strDriversLicense1", "");
        edtLicense.setText(str);
        str = sharedPreferences.getString("strMobilePhone1", "");
        edtMobilePhone.setText(str);
        str = sharedPreferences.getString("strHomePhone1", "");
        edtHomePhone.setText(str);
        str = sharedPreferences.getString("strEMailAddress", "");
        edtEmail.setText(str);
        str = sharedPreferences.getString("strHomeAddress", "");
        edtHomeAddress.setText(str);
        n = sharedPreferences.getInt("nResidentialStatus", 0);
        spnResidentialStatus.setSelection(n);
        
        
        
//        n = sharedPreferences.getInt("nNumberOfDependant1", 0);
//        spnNumberOfDependant.setSelection(n);
        n = sharedPreferences.getInt("nPurposeOfLoan1", 0);
        spnLoanPurpose.setSelection(n);
    	str = sharedPreferences.getString("strOtherPurpose", "");
    	edtOtherPurpose.setText(str);
    }
    
    public void savePreferences() {
   	 	SharedPreferences.Editor editor = sharedPreferences.edit();
   	 	
   	 	editor.putString	("strLoanAmount", 		edtLoanAmount.getText().toString());
   	 	editor.putInt		("nTitle1", 			spnTitle.getSelectedItemPosition());
   	 	editor.putString	("strFirstName1", 		edtFirstName.getText().toString());
   	 	editor.putString	("strMiddleName1", 		edtMiddleName.getText().toString());
   	 	editor.putString	("strSurname1", 		edtSureName.getText().toString());
   	 	editor.putInt		("nResidency", 			spnCitizenShip.getSelectedItemPosition());
   	 	editor.putString	("strDOB", 				btnBirthday.getText().toString());
   	 	editor.putString	("strDriversLicense1", 	edtLicense.getText().toString());
   	 	editor.putString	("strMobilePhone1", 	edtMobilePhone.getText().toString());
   	 	editor.putString	("strHomePhone1", 		edtHomePhone.getText().toString());
   	 	editor.putString	("strEMailAddress", 	edtEmail.getText().toString());
   	 	editor.putString	("strHomeAddress", 		edtHomeAddress.getText().toString());
   	 	editor.putInt		("nResidentialStatus", 	spnResidentialStatus.getSelectedItemPosition());
   	 	
//   	 	editor.putInt		("nNumberOfDependant1", spnNumberOfDependant.getSelectedItemPosition());
   	 	editor.putInt		("nPurposeOfLoan1", 	spnLoanPurpose.getSelectedItemPosition());
   	 	editor.putString	("strOtherPurpose", 	edtOtherPurpose.getText().toString());

   	 	editor.commit();
    }
    
    public void next() {
    	
    	savePreferences();
    	if (!checkInput()) return;
    	
    	GlobalData.personalInfo = new PersonalInfo();
    
    	GlobalData.personalInfo.strLoanAmount 	= edtLoanAmount.getText().toString();
    	GlobalData.personalInfo.strTitle1 		= GlobalData.itemsOfTitle[(int) spnTitle.getSelectedItemId()];
    	GlobalData.personalInfo.strFirstName1	= edtFirstName.getText().toString();
    	GlobalData.personalInfo.strMiddleName1	= edtMiddleName.getText().toString();
    	GlobalData.personalInfo.strSurname1	= edtSureName.getText().toString();
    	GlobalData.personalInfo.strResidency	= GlobalData.itemsOfCitizeShip[(int) spnCitizenShip.getSelectedItemId()];
    	
    	GlobalData.personalInfo.strDOB					= btnBirthday.getText().toString();
    	GlobalData.personalInfo.strDriversLicense1 	= edtLicense.getText().toString();
    	GlobalData.personalInfo.strMobilePhone1		= edtMobilePhone.getText().toString();
    	GlobalData.personalInfo.strHomePhone1			= edtHomePhone.getText().toString();
    	GlobalData.personalInfo.strEMailAddress 		= edtEmail.getText().toString();
    	GlobalData.personalInfo.strResidentialStatus	= GlobalData.itemsOfResidentialStatus[(int) spnResidentialStatus.getSelectedItemId()];
    	
    	GlobalData.personalInfo.strResidentialAddress1 	= edtHomeAddress.getText().toString();
    	/*
    	String strResidentialAddress1
    	String strSuburb1
    	String strState1
    	String strPostcode1
    	*/
    	
//    	GlobalData.personalInfo.strNumberOfDependant1 	= GlobalData.itemsOfNumberDependant[(int) spnNumberOfDependant.getSelectedItemId()];
    	GlobalData.personalInfo.strPurposeOfLoan1		= GlobalData.itemsOfLoanPurpose[(int) spnLoanPurpose.getSelectedItemId()];
    	GlobalData.personalInfo.strOtherPurpose		= edtOtherPurpose.getText().toString();
    	
//    	new MyAsyncTask().execute("signup");
    	
    	this.startActivity(new Intent(this, SubmitActivity.class));
    }

    private boolean checkInput() {
    	
    	String str;

    	str = edtLoanAmount.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input value Loan Amount!");
    		scrollView.scrollTo(0, edtLoanAmount.getTop() - 30);
    		edtLoanAmount.requestFocus();

    		return false;
    	}
    	
    	int nLoanAmount = Integer.parseInt(str);
    	if (nLoanAmount < 1000) {
    		showGeneralAlert("", "The minimum loan amount is $1000.");
    		edtLoanAmount.requestFocus();
    		
    		scrollView.scrollTo(0, edtLoanAmount.getTop() - 30);

    		return false;
    	}
    	
    	str = GlobalData.itemsOfTitle[(int) spnTitle.getSelectedItemPosition()];
    	if (str == "-Select-") {
    		showGeneralAlert("Select", "Please select a Title!");
    		
    		scrollView.scrollTo(0, spnTitle.getTop() - 30);
    		spnTitle.requestFocusFromTouch();
    		
    		return false;
    	}
    	    	
    	str = edtFirstName.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input FirstName!");
    		edtFirstName.requestFocus();
    		
    		scrollView.scrollTo(0, edtFirstName.getTop() - 30);

    		return false;
    	}
    	
    	str = edtSureName.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input SureName!");
    		edtSureName.requestFocus();
    		
    		scrollView.scrollTo(0, edtSureName.getTop() - 30);

    		return false;
    	}
    	
    	str = GlobalData.itemsOfCitizeShip[spnCitizenShip.getSelectedItemPosition()];;
    	if (str == "-Select-") {
    		showGeneralAlert("Select", "Please select a Citizenship!");
    		
    		scrollView.scrollTo(0, spnCitizenShip.getTop() - 30);
    		spnCitizenShip.requestFocusFromTouch();

    		return false;
    	}

    	str = btnBirthday.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Select", "Please input your birthday!");
    		
    		scrollView.scrollTo(0, btnBirthday.getTop() - 30);

    		return false;
    	}
    	
    	str = edtMobilePhone.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input your Mobile phohe number!");
    		edtMobilePhone.requestFocus();
    		
    		scrollView.scrollTo(0, edtMobilePhone.getTop() - 30);

    		return false;
    	}

    	String strFirst;
    	
    	strFirst = str.substring(0, 2);
    	int l = str.length();
    	if (!strFirst.equals("04") || l != 10) {
    		showGeneralAlert("Input", "Your Mobile phohe number has wrong format!");
    		edtMobilePhone.requestFocus();

    		scrollView.scrollTo(0, edtMobilePhone.getTop() - 30);

    		return false;
    	}

    	str = edtHomePhone.getText().toString();
    	
    	if (!str.equals("")) {
    		if (str.length() != 10) {
        		showGeneralAlert("Input", "Your Home phohe number has wrong format!");
        		edtHomePhone.requestFocus();
        		
        		scrollView.scrollTo(0, edtHomePhone.getTop() - 30);

        		return false;
        	}
    		strFirst = str.substring(0, 2);
        	if (!strFirst.equals("02") || str.length() != 10) {
        		showGeneralAlert("Input", "Your Home phohe number has wrong format!");
        		edtHomePhone.requestFocus();

        		scrollView.scrollTo(0, edtHomePhone.getTop() - 30);

        		return false;
        	}
    	}
    	
    	str = edtEmail.getText().toString();
    	if (!str.equals("")) {
    		l = str.length();
        	
        	if (l > 4) {
//        		String strLast = str.substring(l - 4);
//        		if (!strLast.equals(".com")) {
//        			showGeneralAlert("Error", "Your Email address has wrong format");
//        			edtEmail.requestFocus();
//        			return false;
//        		}
        		
        		int k = str.indexOf("@");
        		if (k < 1) {
        			showGeneralAlert("Error", "Your Email address has wrong format");
        			edtEmail.requestFocus();
        			
            		scrollView.scrollTo(0, edtEmail.getTop() - 30);

        			return false;
        		}
        		
        		int k1 = str.indexOf(".com");
        		if (k1 < 3) {
        			showGeneralAlert("Error", "Your Email address has wrong format");
        			edtEmail.requestFocus();
        			
            		scrollView.scrollTo(0, edtEmail.getTop() - 30);

        			return false;
        		}
        		
        		if (k1 - k < 2) {
        			showGeneralAlert("Error", "Your Email address has wrong format");
        			edtEmail.requestFocus();
        			
            		scrollView.scrollTo(0, edtEmail.getTop() - 30);

        			return false;
        		}
        		if (k == l - 5) {
        			showGeneralAlert("Error", "Your Email address has wrong format");
        			edtEmail.requestFocus();
        			
            		scrollView.scrollTo(0, edtEmail.getTop() - 30);

        			return false;
        		}
        			
        	} else {
        		showGeneralAlert("Error", "Your Email address has wrong format");
    			edtEmail.requestFocus();
    			
        		scrollView.scrollTo(0, edtEmail.getTop() - 30);

    			return false;
        	}
    	}
    	    	
    	str = GlobalData.itemsOfResidentialStatus[(int) spnResidentialStatus.getSelectedItemPosition()];
    	if (str == "-Select-") {
    		showGeneralAlert("Select", "Please select a Residential Status!");
    		
    		scrollView.scrollTo(0, spnResidentialStatus.getTop() - 30);
    		spnResidentialStatus.requestFocusFromTouch();

    		return false;
    	}
    	
    	str = edtHomeAddress.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input Full Home Address!");
    		edtHomeAddress.requestFocus();
    		
    		scrollView.scrollTo(0, edtHomeAddress.getTop() - 30);

    		return false;
    	}
    	str = GlobalData.itemsOfLoanPurpose[(int) spnLoanPurpose.getSelectedItemId()];
    	if (str == "-Select-") {
    		showGeneralAlert("Select", "Please select a Loan Purpose!");
    		
    		scrollView.scrollTo(0, spnLoanPurpose.getTop() - 30);
    		spnLoanPurpose.requestFocusFromTouch();

    		return false;
    	}
    	str = edtOtherPurpose.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please give more details!");
    		edtOtherPurpose.requestFocus();
    		
    		scrollView.scrollTo(0, edtOtherPurpose.getTop() - 30);

    		return false;
    	}
    	return true;
    }
    
    public void onBackPressed(){
        // do something here and don't write super.onBackPressed()
    	super.onBackPressed();
    	savePreferences();
    }
}
